package com.ang.http.okHttp;

import com.alibaba.fastjson.JSONObject;
import com.ang.http.entity.HuangliRes;
import com.ang.http.entity.PhoneLocationDataItem;
import com.ang.http.entity.PhoneLocationRes;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component
public class OkHttpHandler {
    @Autowired
//    @Qualifier(value = "simpleOkHttpClient")
    private OkHttpClient simpleOkHttpClient;

    /**
     * get请求获取手机号码归属地
     *
     * @param phone
     */
    public void doGet(String phone) {

        //http://apis.juhe.cn/mobile/get

        //HttpUrl，添加参数
        HttpUrl.Builder httpUrlBuilder = HttpUrl.parse("http://apis.juhe.cn/mobile/get").newBuilder();
//        httpUrlBuilder.addQueryParameter("dtype",urlEncode("json"));
        httpUrlBuilder.addQueryParameter("phone", urlEncode(phone));
        httpUrlBuilder.addQueryParameter("key", urlEncode("fb50ed29c12ca3b5bf173cba6e74f2c4"));

        //Request
        Request request = new Request.Builder()
//                .url("http://apis.juhe.cn/mobile/get")
                .url(httpUrlBuilder.build().toString())
                .header("Content-Type", "application/x-www-form-urlencoded")
                .build();

        //Call
        Call call = simpleOkHttpClient.newCall(request);

        //Response
        try{
            Response response = call.execute();

    //      response.code()== HttpStatus.OK.value()
            if (response.isSuccessful()) {
                String body = response.body().string();
                System.out.println("返回body：" + body);
                System.out.println("-----------------------------");

                ObjectMapper objectMapper = new ObjectMapper();
                JavaType javaTypeResult = objectMapper.getTypeFactory().constructParametricType(PhoneLocationRes.class, PhoneLocationDataItem.class);
                PhoneLocationRes res = objectMapper.readValue(body, javaTypeResult);
                System.out.println(res.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 更多post使用
     * https://blog.csdn.net/qq_34681580/article/details/125157816?spm=1001.2014.3001.5506
     *
     * @param date
     */
    public void doPost(String date) {
        //老黄历接口，key：64c15af55a20e13c2fd3d96d6db415c4
        String key = "64c15af55a20e13c2fd3d96d6db415c4";
        Map params = new HashMap();
        params.put("key", key);
        params.put("date",date);
        JSONObject jsonObject = new JSONObject(params);
        System.out.println("参数："+jsonObject.toJSONString());


        HttpUrl.Builder httpUrlBuilder = HttpUrl.parse("http://v.juhe.cn/laohuangli/d").newBuilder();
        httpUrlBuilder.addQueryParameter("date", urlEncode(date));
        httpUrlBuilder.addQueryParameter("key", urlEncode("64c15af55a20e13c2fd3d96d6db415c4"));

        //RequestBody，请求入参
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), jsonObject.toJSONString());

        //Request
        Request request = new Request.Builder()
                .header("Content-Type","application/x-www-form-urlencoded")
//                .post(requestBody)
//                .url("http://v.juhe.cn/laohuangli/d")
                .url(httpUrlBuilder.toString())
                .build();

        //Call
        Call call = simpleOkHttpClient.newCall(request);

        //Response
        try {
            Response response = call.execute();

            if(response.isSuccessful()){
                String body = response.body().string();

                ObjectMapper objectMapper = new ObjectMapper();
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(HuangliRes.class, HuangliRes.DataItem.class);
                HuangliRes<HuangliRes.DataItem> res = objectMapper.readValue(body, javaType);

                System.out.println(res.toString());

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String urlEncode(String data) {
        try {
            return URLEncoder.encode(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        OkHttpHandler httpHandler = new OkHttpHandler();
        System.out.println(httpHandler.urlEncode("64c15af55a20e13c2fd3d96d6db415c4"));;
    }
}
